package com.woniu.bh.backstage.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.woniu.bh.backstage.dto.LoginManagerDto;
import com.woniu.bh.backstage.dto.ManagerDto;
import com.woniu.bh.backstage.dto.PageResult;
import com.woniu.bh.backstage.param.*;
import com.woniu.bh.backstage.service.IManagerService;
import com.woniu.bh.common.core.domain.backstage.Manager;
import com.woniu.bh.common.core.dto.ResultDto;
import com.woniu.bh.common.core.exception.ProjectException;
import com.woniu.bh.common.core.exception.ProjectExceptionResult;
import com.woniu.bh.common.core.util.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cxb
 * @since 2020-10-13
 */
@RestController
@RequestMapping("/manager")
@Slf4j
@Api(value = "后台接口", tags = "管理员管理")
public class ManagerController {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @Autowired
    private IManagerService managerService;

    @PostMapping("login")
    @ApiOperation(value = "管理员登录")
    public ResultDto backlogin(@RequestBody LoginParam loginParam){
        ManagerParam managerParam = new ManagerParam();
        managerParam.setName(loginParam.getName());
        managerParam.setPass(loginParam.getPass());
        ResultDto loginResult = managerService.login(managerParam);
        if(loginResult.isSuccess()) {
            //登陆成功
            Map<String, Object> maps = new HashMap<>();
            maps.put("id", loginResult.getObject());
            String token = JwtUtil.createToken(maps, 60*60*24);
            Manager manager = (Manager)loginResult.getObject();
            LoginManagerDto loginManagerDto = new LoginManagerDto();
            BeanUtils.copyProperties(manager,loginManagerDto);
            loginManagerDto.setToken(token);
            return ResultDto.success(loginResult.getCode(),loginResult.getMessage(),loginManagerDto);
        }else{
            //登陆失败
            return loginResult;
        }
    }

    @GetMapping("getcode")
    @ApiOperation(value = "管理员获取验证码")
    public ResultDto backgetcode(@RequestParam String phone){
        //根据手机号查询是否有用户绑定,有则发送并返回验证码
        ManagerDto managerDto = managerService.selectByPhone(phone);
        if (managerDto==null){
            return ResultDto.builder().code(ProjectExceptionResult.USER_NOT_EXSIT.getCode()).message(ProjectExceptionResult.USER_NOT_EXSIT.getMessage()).build();
        }
        String code = managerService.getVerifyCode(phone);
        if (StringUtils.isNotEmpty(code)){
            return ResultDto.builder().code(200).message("执行成功").object(code).success(true).build();
        }else {
            return ResultDto.builder().code(ProjectExceptionResult.MESSAGE_SEND_FAILED.getCode()).message(ProjectExceptionResult.MESSAGE_SEND_FAILED.getMessage()).object(null).build();
        }
    }

    @PostMapping("verify")
    @ApiOperation(value = "管理员验证验证码")
    public ResultDto backverifycode(@RequestBody VerifyPhoneParam verifyPhoneParam){
        ManagerDto managerDto = managerService.selectByPhone(verifyPhoneParam.getPhone());
        if (managerDto==null){
            return ResultDto.builder().code(ProjectExceptionResult.USER_NOT_EXSIT.getCode()).message(ProjectExceptionResult.USER_NOT_EXSIT.getMessage()).build();
        }
        //从redis中取出
        String savedCode  = redisTemplate.opsForValue().get(verifyPhoneParam.getPhone());
        System.out.println(savedCode+"--"+verifyPhoneParam.getInputCode());
        if (!StringUtils.isNotEmpty(savedCode)){
            return ResultDto.builder().code(ProjectExceptionResult.MESSAGE_VERIFYCODE_EXPIRED.getCode()).message(ProjectExceptionResult.MESSAGE_VERIFYCODE_EXPIRED.getMessage()).build();
        }
        if (savedCode.equals(verifyPhoneParam.getInputCode())){
            return ResultDto.builder().code(1).message("执行成功").success(true).object(verifyPhoneParam.getPhone()).build();
        }else {
            return ResultDto.builder().code(ProjectExceptionResult.MESSAGE_VERIFY_FAILED.getCode()).message(ProjectExceptionResult.MESSAGE_VERIFY_FAILED.getMessage()).build();
        }
    }

    @PostMapping("modifypwd")
    @ApiOperation(value = "管理员修改密码")
    public ResultDto backmodifypwd(@RequestBody ModifyPwdParam modifyPwdParam){
        String newpwd = modifyPwdParam.getNewPassword();
        String repeqtpwd = modifyPwdParam.getRepeatPassword();
        if(!newpwd.equals(repeqtpwd)){
            return ResultDto.fail(ProjectExceptionResult.USER_REPEAT_PASSWORD_NOT_SAME.getCode(),ProjectExceptionResult.USER_REPEAT_PASSWORD_NOT_SAME.getMessage());
        }
        managerService.modifyPwd(modifyPwdParam);
        return ResultDto.builder().code(1).message("执行成功").success(true).build();
    }

    @GetMapping("query")
    @ApiOperation(value = "管理员查询个人信息")
    public ResultDto backquery(HttpServletRequest request){
        System.out.println(new Date().getTime());
        String token = request.getHeader("X-Token");
        Map<String,Object> map = JwtUtil.parseToken(token);
        Integer id = (Integer)map.get("id");
        System.out.println("用户id"+id);
        ManagerDto managerDto = managerService.selectManagerById(id);
        return ResultDto.success(managerDto);
    }

    @GetMapping("logout")
    @ApiOperation(value = "管理员注销")
    public ResultDto backlogout(){
        log.info("用户注销");
        return ResultDto.success(ProjectExceptionResult.SUCCESS);
    }

    //以下为超管功能
    @GetMapping("querylist")
    @ApiOperation(value = "查询管理员列表")
    public ResultDto backquerylist(@RequestBody QueryManagerParam queryManagerParam){
        log.info("传入数据{}", queryManagerParam.toString());
        IPage<ManagerDto> iPage = managerService.selectPage(queryManagerParam.getPageIndex(),queryManagerParam.getPageSize(),queryManagerParam.getManagerStatus(),queryManagerParam.getDateAfter(),queryManagerParam.getDateBefore());
        return ResultDto.success(iPage);
    }

    //以下为超管功能
    @PostMapping("freeze")
    @ApiOperation(value = "冻结管理员")
    public ResultDto backfreeze(@RequestParam Integer id){
        log.info("传入数据{}"+id);
        ManagerDto managerDto = managerService.freezeManager(id);
        if (managerDto!=null){
            return ResultDto.success(managerDto);
        }
        return ResultDto.fail(ProjectExceptionResult.USER_NOT_EXSIT);
    }

    //以下为超管功能
    @PostMapping("unfreeze")
    @ApiOperation(value = "解冻管理员")
    public ResultDto backunfreeze(@RequestParam Integer id){
        log.info("传入数据{}"+id);
        ManagerDto managerDto = managerService.unFreezeManager(id);
        if (managerDto!=null){
            return ResultDto.success(managerDto);
        }
        return ResultDto.fail(ProjectExceptionResult.USER_NOT_EXSIT);
    }

    //以下为超管功能
    @PostMapping("add")
    @ApiOperation(value = "新增管理员")
    public ResultDto backAddManager(@RequestBody AddManagerParam addManagerParam){
        log.info("传入数据{}"+addManagerParam.toString());
        return managerService.addManager(addManagerParam);
    }
}

